﻿var tree = $('#jstree_folders'),
	_grid = $('#jgTable');
var Data = [],
	Folder = '',
    Name = '';

gridWidth = $('.u_field_tables');

$(function(){

	myAlert('点击左上角按钮可切换其他文件夹');

	treeInit();
	requestAjax01();
	_gridInit();
	$('li[data-opt="add"').on('click', addPics);
	$('li[data-opt="edit"]').on('click', function(){
        var rowId = _grid.jqGrid('getGridParam', 'selrow');
        editCode(rowId);
    });
	$("li[data-opt='opt_search']").find(">i").on('click', function () {
		gridSearch.Content.SearchText = $("#opt_search").find(">input").val();
        _grid.jqGrid("setGridParam",{postData: gridSearch}).trigger("reloadGrid");
	});

	tree.on("changed.jstree", function (e, data) {
		if (data.action === 'select_node') {
			Folder = data.node.li_attr.Code;
            Name = data.node.li_attr.Name;
			gridSearch.Content.Folder = Folder;
			_grid.jqGrid("setGridParam",{postData: gridSearch}).trigger("reloadGrid");
		}else if(data.action === 'deselect_all') {
			console.log('加载完成')
            var Selected = $('li[code="ProductImages"]');
            Selected.find('>a').trigger('click');
		}
	});

	$('.modal-data').draggable({cancel:'.u_modal_body, input'});

	$('.expBtn').on('click', function(){
		if($(this).hasClass('exp')){
			$(this).parent().parent().css({'margin-left':'420px'});
			$(this).removeClass('exp');
			gridSize();
		}else{
			$(this).parent().parent().css({'margin-left':'3px'});
			$(this).addClass('exp');
			gridSize();
		}
	});
	
	$('input[type="file"]').on('change',function(){
		$('.nextPic').attr('src', getObjectURL(this.files[0]));
	});

});

function context_menu(){
    var items = {
        'New': {
            'label': '添加',
            'action': nodeEdit
        }
    };
    return items;
}
function requestAjax01(){   //MDM001902
    $.ajax({
        async: false,
        type: "post",
        url: mdmPath + "/MDM0019/MDM001902",
        data: {
            Method: 'Q',
            Tonken: postData.Tonken,
            UserCode: postData.UserCode,
            BrowserID: postData.BrowserID,
            Source: postData.Source
        },
        dataType: "json",
        success: function(re) {
            loadAjax01(re);
        }
    });
}
function loadAjax01(re){
	re.Status == -999 && alert_QX($('body'),re.Message);
    Data = re.Content;
    //Data = [];
    if(Data.length>0){
        treeRefresh();    
    }
}


function picFormatter(cellvalue, options, rowdata){
	return '<img src="'+rowdata.PicturePath+'?temp='+Math.random()+'" style="width:100px">';	
}
function alarmFormatter(cellvalue, options, rowdata){
	var grid = $(this);
	if(JSON.stringify(rowdata)!=='{}'){
		cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_pic"><i class="fa fa-file-image-o" title="替换"></i></a>'+
			'&nbsp;<a href="javascript:0" opt-data="'+grid[0].id+'_edit"><i class="fa fa-pencil" title="编辑"></i></a>'+
			'&nbsp;<a href="javascript:0" opt-data="'+grid[0].id+'_delete"><i class="fa fa-trash-o" title="删除"></i></a>';
	}else{
		cellvalue = '';
	}
	return cellvalue;
}
function _gridInit(){	//MDM002002
    var _gridData = Object.create(gridData);
    _gridData.url = mdmPath + '/MDM0020/MDM002002';
	_gridData.colModel = [
        {label:'代码', name:'Code'},
        {label:'名称', name:'Name'},
		{label:'文件夹', name:'Folder', hidden:true},
		{label:'图片', name:'PicturePath', formatter: picFormatter},
        {label:'操作', name:'Options', width:80, align:'center', formatter: alarmFormatter}
    ];
	_gridData.sortname = 'Code';
	var _postData = {
		Method: 'Q',
        Content:{
			Folder: '',
            SearchText: ''
        }
    };
    for(i in postData){
        _postData[i] = postData[i];
    }
	_gridData.beforeRequest = function(){
        _gridData.grid.jqGrid("setGridParam", {
            postData : _postData,
        });
    };
	_gridData.loadComplete = function(xhr){
		if(xhr.Status == '-999') {
			alert_QX($('body'),xhr.Message)
		}
		$('a[opt-data="jgTable_pic"]').unbind('click').bind('click', function(){
            var rowId = $(this).parent().parent()[0].id;
            picCode(rowId);
        });
        $('a[opt-data="jgTable_edit"]').unbind('click').bind('click', function(){
            var rowId = $(this).parent().parent()[0].id;
            editCode(rowId);
        });
        $('a[opt-data="jgTable_delete"]').unbind('click').bind('click', function(){
            var rowId = $(this).parent().parent()[0].id;
            deleteCode(rowId);
        });
		gridSize();
    };
    gridInit(_gridData);
    gridSearch = _postData;
};

//Options
function addPics(){
	formdata.Folder = Folder;
	myUpload();
	$('#modal-overlay2').removeClass('hidden');
}
function picCode(rowId){
	if(rowId){  //判断是否选中有效行
		var rowData = _grid.jqGrid('getRowData', rowId);
		var img = rowData.PicturePath;
		$('.prevPic').attr('src', img.split('"')[1]);
		$('.nextPic').attr('src', '../../asset/images/preview.png');
		$('input[type="file"]').val('');
		formdata = {
			"Folder": rowData.Folder,
			"Code": rowData.Code,
			"PicturePath": img.split('"')[1]
		}
		for(i in postData){
			formdata[i] = postData[i]
		}
		//console.log(formdata);
		$('#uploader2').unbind('click').bind('click', function(){
			var v = $('input[type="file"]').val();
			var formData = new FormData($('#uploadForm')[0]);
			formData.append("Folder", formdata.Folder);
			formData.append("Code", formdata.Code);
			formData.append("PicturePath", formdata.PicturePath);
			formData.append("Tonken", formdata.Tonken);
			formData.append("UserCode", formdata.UserCode);
			formData.append("BrowserID", formdata.BrowserID);
			formData.append("Source", formdata.Source);
			if(v){
				$.ajax({
					url: mdmPath+'/MDM0020/MDM002006',
					type: 'post',
					//async: false,  
					cache: false,
					data: formData,
					success: function(re){
						if(re == ''){
							_grid.trigger("reloadGrid");
							$('input[type="file"]').val('');
							$('#modal-overlay3').addClass('hidden');
							myAlert('替换成功');
						}else{
							myAlert('替换失败');
						}
					},
					contentType: false,  
					processData: false,  
				});
			}else{
				myAlert('请选择要上传的图片');
			}
		});
		$('#modal-overlay3').removeClass('hidden');
	}else{
        myAlert('请选择您要编辑的数据');
    }
}
function editCode(rowId){
	if(rowId){  //判断是否选中有效行
		var rowData = _grid.jqGrid('getRowData', rowId);
		$('#m_Code').val(rowData.Code).attr('disabled', true);
        $('#m_Name').val(rowData.Name);
		$('#modal-overlay1').removeClass('hidden');
		var postData0e = Object.create(postData);
        postData0e.Method = 'U';
		$('#submitBtn').unbind('click').bind('click', function(){
			postData0e.Content = {
				Code: $('#m_Code').val(),
				Name: $('#m_Name').val()
			};
			$.ajax({
				type: 'post',
				url: mdmPath + '/MDM0020/MDM002004',
				data: postData0e,
				dataType: 'json',
				success: function(re){
					if(re.Status == 200){
						_grid.trigger("reloadGrid");
						$('#modal-overlay1').addClass('hidden');
						myAlert('修改成功');
					}else{
						myAlert(re.Message);
					}
				}
			});
		});
	}else{
        myAlert('请选择您要编辑的数据');
    }
}
function deleteCode(rowId){
	if(rowId){  //判断是否选中有效行
		var rowData = _grid.jqGrid('getRowData', rowId);
		console.log(rowData)
		myAlert('暂无删除功能');
	}else{
        myAlert('请选择您要删除的数据');
    }
}

